<template>
  <el-breadcrumb separator="/" class="breadcrumb">
    <el-breadcrumb-item
      v-for="(item, index) in breadcrumbList"
      :key="item.path || index"
      :to="index === breadcrumbList.length - 1 ? undefined : item.path"
      :class="{ 'is-last': index === breadcrumbList.length - 1 }"
    >
      <el-icon v-if="getIconComponent(item.icon)" class="breadcrumb-icon">
        <component :is="getIconComponent(item.icon)" />
      </el-icon>
      <span>{{ item.title }}</span>
    </el-breadcrumb-item>
  </el-breadcrumb>
  </template>

<script setup>
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { House, User, Document } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

const ICON_MAP = { House, User, Document }
const getIconComponent = (name) => (name && ICON_MAP[name]) || null

// 面包屑列表
const breadcrumbList = computed(() => {
  // 过滤掉布局根路由 '/' 与具体首页 '/home'，避免“首页”重复
  const matched = route.matched.filter(item => {
    const hasTitle = item.meta && item.meta.title
    const isRoot = item.path === '/'
    const isHome = item.path === '/home'
    return hasTitle && !isRoot && !isHome
  })

  // 如果当前路由就是首页，只显示一个首页
  if (route.path === '/home') {
    return [{ path: '/home', title: '首页', icon: 'House' }]
  }

  // 总是以首页开头，然后拼接父级及当前
  const breadcrumbs = [{ path: '/home', title: '首页', icon: 'House' }]

  matched.forEach(match => {
    // 如果该路由本身没有页面（仅作为模块/目录），跳到它的第一个子路由
    let targetPath = match.path
    if (!match.components && Array.isArray(match.children) && match.children.length > 0) {
      const firstChild = match.children[0]
      if (firstChild.path) {
        // 处理相对子路径
        targetPath = targetPath.endsWith('/')
          ? `${targetPath}${firstChild.path}`
          : `${targetPath}/${firstChild.path}`
      }
    }
    breadcrumbs.push({
      path: targetPath,
      title: match.meta.title,
      icon: match.meta.icon
    })
  })

  return breadcrumbs
})

// 点击面包屑项
const handleBreadcrumbClick = (item) => {
  if (item.path && item.path !== route.path) {
    router.push(item.path)
  }
}
</script>

<style lang="scss" scoped>
.breadcrumb {
  .el-breadcrumb__item {
    .el-breadcrumb__inner {
      display: flex;
      align-items: center;
      gap: 4px;
      color: #606266;
      font-size: 14px;
      transition: color 0.3s;
      
      &:hover {
        color: #409eff;
      }
    }
    
    &.is-last .el-breadcrumb__inner {
      color: #303133;
      font-weight: 500;
      cursor: default;
      
      &:hover {
        color: #303133;
      }
    }
  }
  
  .breadcrumb-icon {
    font-size: 14px;
  }
  
  .el-breadcrumb__separator {
    color: #c0c4cc;
    margin: 0 8px;
    font-size: 12px;
  }
}
</style>